package com.cxhc.system.service.app.impl;

import com.alibaba.fastjson2.JSONObject;
import com.cxhc.common.utils.http.HttpUtils;
import com.cxhc.system.domain.app.WeatherApp;
import com.cxhc.system.service.app.IWeatherService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WeatherAppServiceImpl implements IWeatherService {

    // 天气情况查询接口地址
    public static String API_URL = "http://apis.juhe.cn/simpleWeather/query";
    // 接口请求Key
    public static String API_KEY = "db40a3e8d0ead2652bb1dfa0f4b8f307";

    private static final Logger log = LoggerFactory.getLogger(WeatherAppServiceImpl.class);

    @Override
    public WeatherApp getWeather(String city) {

        Map<String, Object> params = new HashMap<>();//组合参数
        params.put("city", city);
        params.put("key", API_KEY);
        String httpParams = HttpUtils.urlencode(params);
        String response = HttpUtils.sendGet(API_URL, httpParams);
        WeatherApp weatherApp = new WeatherApp();
        try {
            JSONObject jsonObject = JSONObject.parseObject(response);
            int error_code = jsonObject.getIntValue("error_code");
            if (error_code == 0) {
                log.info("调用获取天气接口成功");
                JSONObject result = jsonObject.getJSONObject("result");
                JSONObject realtime = result.getJSONObject("realtime");

                //城市
                weatherApp.setCity(result.getString("city"));
                //空气质量
                weatherApp.setAqi(realtime.getString("aqi"));
                //风向
                weatherApp.setDirect(realtime.getString("direct"));
                //湿度
                weatherApp.setHumidity(realtime.getString("humidity"));
                //天气
                weatherApp.setInfo(realtime.getString("info"));
                //风力
                weatherApp.setPower(realtime.getString("power"));
                //温度
                weatherApp.setTemperature(realtime.getString("temperature"));
                log.info("天气返回信息---{}",weatherApp.toString());

            } else {
                System.out.println("调用接口失败：" + jsonObject.getString("reason"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return weatherApp;
    }

}
